package com.bluetool.debby.bluetoothjob;

import android.Manifest;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.bluetool.debby.bluetoothjob.Utils.BlueToothUtil;
import com.bluetool.debby.bluetoothjob.adapter.BlueAdapter;
import com.bluetool.debby.bluetoothjob.listener.OnBlueToothListener;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;

import java.util.ArrayList;
import java.util.List;

import static com.bluetool.debby.bluetoothjob.Utils.BlueToothUtil.REQUEST_ENABLE;
import static com.bluetool.debby.bluetoothjob.Utils.BlueToothUtil.REQUEST_LOCATION_ENABLE;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    //View
    private RecyclerView rv_blue_list;
    private BlueAdapter adapter;
    //蓝牙列表
    private List<BleDevice> deviceList;
    private final int MY_PERMISSION_REQUEST_CONSTANT = 110;
    //核心蓝牙通信
    BluetoothGatt blueGatt;
    //服务内容
    List<BluetoothGattService> serviceList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);
        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(5, 3000)
                .setOperateTimeout(5000);
        initView();
        initData();
    }

    private void initView() {
        rv_blue_list = findViewById(R.id.rv_blue_list);
        findViewById(R.id.bt_connect).setOnClickListener(this);
        findViewById(R.id.bt_refresh).setOnClickListener(this);
    }


    private void initData() {
        BleManager.getInstance().isSupportBle();
        BleManager.getInstance().isBlueEnable();
        //蓝牙list
        deviceList = new ArrayList<>();
        adapter = new BlueAdapter(this, deviceList, new OnBlueToothListener() {
            @Override
            public void onItemClick(BleDevice device) {
                connectDevice(device);
            }
        });

        rv_blue_list.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false));
        rv_blue_list.setAdapter(adapter);
    }


    //连接指定蓝牙设备
    private void connectDevice(BleDevice device) {
        BleManager.getInstance().connect(device, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                showToast("onStartConnect");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                showToast("onConnectFail");
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                showToast("onConnectSuccess");
                blueGatt = gatt;
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                showToast("onDisConnected");
            }
        });
    }




    //开启蓝牙
    private void open() {
        BlueToothUtil.openBle(this);
        BlueToothUtil.openLocation(this);

        if (Build.VERSION.SDK_INT >= 6.0) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION
                            , Manifest.permission.ACCESS_COARSE_LOCATION},
                    MY_PERMISSION_REQUEST_CONSTANT);
        }
    }


    //刷新数据
    private void refresh() {
        deviceList.clear();
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {

            }

            @Override
            public void onScanning(BleDevice bleDevice) {

            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                deviceList.addAll(scanResultList);
                Log.e("onScanFinished", "onScanFinished=" + scanResultList.size());

                showDevices();
            }
        });
    }

    private void showDevices() {
        adapter.notifyDataSetChanged();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_ENABLE:
                    showToast("蓝牙开启成功");
                    break;
                case REQUEST_LOCATION_ENABLE:
                    showToast("定位开启成功");
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case MY_PERMISSION_REQUEST_CONSTANT: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    refresh();
                }
            }
            break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_connect:
                open();
                break;
            case R.id.bt_refresh:
                refresh();
                break;
        }
    }
}
